﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Configuration;
using System.Windows.Forms;
using System.Net;
using QuickApp;
using QA.WindowsForms;
using TED;

namespace TEDTalksDownloadManager
{
    public partial class frmTedTalks : Form
    {
        #region # Constructor #
        public frmTedTalks()
        {
            InitializeComponent();
            tedManager = new TalkManager();
            this.ContextMenuStrip = ctxAppSettings;
            this.grdTalks.ContextMenuStrip = ctxDownload;
        }
        #endregion

        #region - Private variables -
        private bool bindTalks = false;
        private frmDownloader downloader = null;
        private TalkManager tedManager = null;
        #endregion

        #region - Private methods -
        private void initializeDownloader()
        {
            downloader = new frmDownloader();
            downloader.Owner = this;
        }
        private void setGridView(DataGridView grd)
        {
            grd.AutoGenerateColumns = false;
            grd.RowHeadersVisible = false;
        }
        private void loadDataSet()
        {
            string pathOfDataFiles = ConfigurationManager.AppSettings.Get(TEDAppSettings.DataFilePathAppSetting);
            if (!tedManager.LoadData(pathOfDataFiles))
            {
                frmConverter con = new frmConverter();
                con.ShowDialog();
                tedManager.LoadData(pathOfDataFiles);
            }
        }
        private WebClient getWebClient(DataRow dr)
        {
            WebClient wc = new WebClient();
            wc.DownloadFileCompleted += delegate(object source, AsyncCompletedEventArgs ev)
            {
                dr[FieldNames.Status] = (int)TalkStatus.Downloaded;
                tedManager.SaveData(ConfigurationManager.AppSettings.Get(TEDAppSettings.DataFilePathAppSetting));
            };
            return wc;
        }
        private void downloadSelectedTalk()
        {
            DataRow currentDownloadRow = grdTalks.GetSelectedRows()[0];
            string url = currentDownloadRow[FieldNames.URL].ToString();
            string filePath = tedManager.GetDownloadPath(grdThemes.GetSelectedRows()[0][FieldNames.Theme].ToString(), ConfigurationManager.AppSettings.Get(TEDAppSettings.DownloadFilePathAppSetting));
            string fileName = Path.GetFileNameWithoutExtension(currentDownloadRow[FieldNames.Name].ToString()) + " - " + currentDownloadRow[FieldNames.Year].ToString() + Path.GetExtension(currentDownloadRow[FieldNames.Name].ToString());
            fileName = Path.Combine(filePath, fileName);
            if (downloader == null || downloader.IsDisposed)
                initializeDownloader();
            downloader.Show();
            downloader.Download(getWebClient(currentDownloadRow), fileName, url);
        }
        private void changeFolderAppSetting(string appSetting,string heading)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = heading;
            fbd.SelectedPath = ConfigurationManager.AppSettings.Get(appSetting);
            if (fbd.ShowDialog() == DialogResult.OK)
                General.ChangeAppSetting(appSetting, fbd.SelectedPath);
        }
        #endregion

        //#region - Public properties / variables - 
        //#endregion

        //#region - Public methods - 
        //#endregion

        #region - Bind Methods -
        private void bindThemesGrid()
        {
            if (tedManager.Themes != null)
            {
                bindTalks = false;
                grdThemes.DataSource = tedManager.Themes;
                bindTalks = true;
                bindTalksGrid();
            }
        }
        private void bindTalksGrid()
        {
            if (tedManager.Talks != null && bindTalks)
            {
                DataRow[] selectedTheme = grdThemes.GetSelectedRows();
                if (selectedTheme != null && selectedTheme.Length > 0)
                {
                    DataView talkView = new DataView(tedManager.Talks);
                    talkView.RowFilter = FieldNames.ThemeId + " = " + Convert.ToInt32(selectedTheme[0][FieldNames.ThemeId]);
                    talkView.Sort = FieldNames.Year+" DESC";
                    grdTalks.DataSource = talkView;
                    grdTalks.ResizeToFields();
                    grdTalks.AddLastColumnToDataGridView();
                }
            }
        }
        #endregion

        #region - Form Events -
        // This region is for event handler methods that are called without the user knowing about it.
        // Such as the page loading.
        private void frmTedTalks_Load(object sender, EventArgs e)
        {
            loadDataSet();
            setGridView(grdThemes);
            setGridView(grdTalks);
            bindThemesGrid();
        }
        private void grdThemes_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            bindTalksGrid();
        }
        private void grdTalks_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0 && Convert.ToInt32(grdTalks.Rows[e.RowIndex].Cells["colStatus"].Value) == (int)TalkStatus.Downloaded)
            {
                grdTalks.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.LightBlue;
                grdTalks.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
            }
        }
        #endregion

        #region - Control Methods -
        // This region is for event handler methods that are called knowingly by the user.
        // Such as a button being clicked.
        private void grdTalks_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            downloadSelectedTalk();
        }
        private void mnuDownload_Click(object sender, EventArgs e)
        {
            downloadSelectedTalk();
        }
        private void downloadPathToolStripMenuItem_Click(object sender, EventArgs e)
        {
            changeFolderAppSetting(TEDAppSettings.DownloadFilePathAppSetting,"Select new folder for download location.");
        }
        private void dataPathToolStripMenuItem_Click(object sender, EventArgs e)
        {
            changeFolderAppSetting(TEDAppSettings.DataFilePathAppSetting, "Select new location of data files.");
        }
        #endregion
    }
}
